<template>
  <div class="page-container">
    <div class="user-info-container">
      <div class="header">
        <h2>个人中心</h2>
        <el-button type="primary" link @click="handleEdit" v-if="!isEditing">
          编辑
        </el-button>
      </div>

      <div class="user-avatar">
        <el-avatar :size="100" :src="userForm.avatar">
          <img src="@/assets/bg/bg2.jpg" />
        </el-avatar>
        <div v-if="isEditing" class="avatar-upload">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <el-button size="small">更换头像</el-button>
          </el-upload>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        :disabled="!isEditing"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="userForm.realName"
                placeholder="请输入真实姓名"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入电话号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地址">
          <el-form-item prop="region">
            <el-cascader
              v-model="userForm.region"
              :options="regionOptions"
              placeholder="请选择所在地区"
            />
          </el-form-item>
          <el-form-item prop="detailAddress">
            <el-input
              v-model="userForm.detailAddress"
              placeholder="请输入详细地址"
              style="margin-top: 10px"
            />
          </el-form-item>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="userForm.birthday"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="userForm.gender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="male" />
                <el-option label="女" value="female" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="过敏史" prop="allergy">
          <el-input
            v-model="userForm.allergy"
            type="textarea"
            :rows="2"
            placeholder="请输入过敏史"
          />
        </el-form-item>

        <el-form-item label="既往病史" prop="medicalHistory">
          <el-input
            v-model="userForm.medicalHistory"
            type="textarea"
            :rows="2"
            placeholder="请输入既往病史"
          />
        </el-form-item>

        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input
            v-model="userForm.emergencyContact"
            placeholder="请输入紧急联系人姓名"
          />
        </el-form-item>

        <el-form-item label="紧急联系电话" prop="emergencyPhone">
          <el-input
            v-model="userForm.emergencyPhone"
            placeholder="请输入紧急联系电话"
          />
        </el-form-item>

        <el-form-item v-if="isEditing" class="form-buttons">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const isEditing = ref(false)
const formRef = ref(null)

const userForm = reactive({
  username: 'Admin',
  realName: '张三',
  email: 'example@qq.com',
  phone: '18234567890',
  region: ['江苏省', '苏州市', '虎丘区'],
  detailAddress: '幸福路123号',
  birthday: '1990-01-01',
  gender: 'male',
  allergy: '头孢',
  medicalHistory: '无',
  emergencyContact: '李四',
  emergencyPhone: '13812345678',
  avatar: '',
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  region: [
    {
      required: true,
      type: 'array',
      message: '请选择所在地区',
      trigger: 'change',
    },
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
  ],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  allergy: [{ required: false }],
  medicalHistory: [{ required: false }],
  emergencyContact: [{ required: false }],
  emergencyPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
}

// 保存原始数据
const originalData = { ...userForm }

// 处理头像上传成功
const handleAvatarSuccess = (response) => {
  userForm.avatar = response.url
  ElMessage.success('头像上传成功')
}

const handleEdit = () => {
  isEditing.value = true
}

const handleSave = async () => {
  if (!formRef.value) return

  console.log('表单数据：', userForm) // 添加这行来检查数据
  try {
    await formRef.value.validate()
    await saveUserInfo(userForm)
    isEditing.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    if (error.fields) {
      // 显示具体的验证错误信息
      const errorFields = Object.keys(error.fields)
      const errorMsg = errorFields
        .map((field) => {
          return error.fields[field][0].message
        })
        .join('\n')
      ElMessage.error(errorMsg)
    } else {
      ElMessage.error('保存失败，请检查输入内容是否正确')
    }
  }
}

const handleCancel = () => {
  Object.assign(userForm, originalData)
  isEditing.value = false
}

// 模拟地区选项数据
const regionOptions = [
  {
    value: '江苏省',
    label: '江苏省',
    children: [
      {
        value: '连云港市',
        label: '连云港市',
        children: [
          { value: '海州区', label: '海州区' },
          { value: '连云区', label: '连云区' },
        ],
      },
    ],
  },
  // ... 其他省市区数据
]

const saveUserInfo = async (formData) => {
  try {
    // 这里添加实际的保存逻辑，例如调用API
    console.log('保存的表单数据：', formData)
    // 模拟异步操作
    await new Promise((resolve) => setTimeout(resolve, 1000))
    return Promise.resolve()
  } catch (error) {
    return Promise.reject(error)
  }
}
</script>

<style scoped>
.page-container {
  height: 100%;
  overflow-y: auto;
}
.user-info-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.info-card {
  max-width: 1000px;
  margin: 0 auto;
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.user-avatar {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-upload {
  margin-top: 10px;
}

.form-buttons {
  margin-top: 30px;
  text-align: center;
}

.el-form-item {
  margin-bottom: 22px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-form-item.is-error .el-input__inner) {
  border-color: #f56c6c;
}
</style>
